import 'package:flutter/material.dart';
import 'package:osc/common/MyTextStyle.dart';
import 'package:osc/data/repository/repository.dart';
import 'package:osc/common/osc_user_manager.dart';
import 'package:osc/models/entity/osc_base_list_entity.dart';
import 'package:osc/models/entity/osc_event_list_entity.dart';
import 'package:osc/models/pop_result/pop_result.dart';
import 'package:osc/res/dimens.dart';
import 'package:osc/res/strings.dart';
import 'package:osc/ui/pages/account/login_page.dart';
import 'package:osc/ui/pages/post/post_detail_page.dart';
import 'package:osc/ui/widgets/image_loader.dart';
import 'package:osc/ui/widgets/no_data_widget.dart';
import 'package:osc/ui/widgets/real_rich_text.dart';
import 'package:osc/ui/widgets/small_widgets.dart';
import 'package:osc/utils/navigator_util.dart';
import 'package:osc/utils/pd_util.dart';
import 'package:osc/utils/string_util.dart';
import 'package:pull_to_refresh/pull_to_refresh.dart';

///活动
class EventList extends StatefulWidget {
  final int authorId;

  const EventList({Key key, @required this.authorId}) : super(key: key);


  @override
  State<StatefulWidget> createState() {
    return new EventListState(authorId);
  }
}

class EventListState extends State<EventList> {
  final int authorId;
  EventListState(this.authorId);

  HttpRepository httpRepository;
  String pageToken;
  int size = 0;
  int bannerCount = 3;
  bool isLoadedData = false;


  double paddingChildVertical = Dimens.gap_view_normal;


  List<OscEventListEntity> list;

  RefreshController controller = RefreshController(initialRefresh: true);


  @override
  void initState() {
    super.initState();
    httpRepository = HttpRepository();
  }

  @override
  void dispose() {
    super.dispose();
    controller.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return SmartRefresher(
      controller: controller,
      onRefresh: refresh,
      onLoading: loadMore,
      enablePullUp: true,
      child: buildListView(),
    );
  }

  buildListView(){
    return ListView.separated(
      itemBuilder: (BuildContext context, int index) {
        if (size == 0) {
          return NoDataWidget();
        } else {
          return buildListItem(index);
        }
      },
      separatorBuilder: (BuildContext context, int index) {
        return SmallWidgets.buildLine();
      },
      itemCount: isLoadedData && size == 0? 1 : size,
    );
  }

  buildListItem(int index){
    OscEventListEntity item = list.elementAt(index);
    String imageUrl;
    if(item.images != null && item.images.length > 0 && !StringUtil.isEmpty(item.images.elementAt(0).thumb)){
      imageUrl = item.images.elementAt(0).thumb;
    } else {
      imageUrl = item.image.href[0];
    }
    return GestureDetector(
      onTap: (){
        jump2PageForResult(PostDetailPage(id: item.id, type: 2,));
      },
      child: Container(
        color: Colors.white,
        height: Dimens.view_event_list_image_height + Dimens.gap_activity_horizontal*2,
        padding: EdgeInsets.all(Dimens.gap_activity_horizontal),
        child: Row(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: <Widget>[
            Container(
              width: Dimens.view_event_list_image_width,
                height: Dimens.view_event_list_image_height,
                padding: EdgeInsets.only(right: Dimens.gap_view_normal),
              child: ImageLoader(url: imageUrl, width: Dimens.view_event_list_image_width, height: Dimens.view_event_list_image_height, fit: BoxFit.contain,),
            ),
            Expanded(
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  mainAxisSize: MainAxisSize.max,
                  children: <Widget>[
                    Expanded(child: Text(item.title, style: MyTextStyle.USER_LIST_TITLE,)),
                    Text(item.pubDate, style: MyTextStyle.LIST_BOTTOM,),
                  ],
                ),
            ),
          ],
        ),
      ),
    );
  }

  buildTitle(String title){
    return buildText(title, Colors.black, Dimens.font_sp14);
  }

  buildTextSpan(String text){
    return TextSpan(
      text: text,
      style: TextStyle(color: Colors.black, fontSize: Dimens.font_sp14,),
    );
  }

  buildImageSpan(String imageName, EdgeInsets margin){
    return ImageSpan(
      AssetImage(PdUtil.getImagePath(imageName)),
      imageWidth: Dimens.view_item_tag_height_small,
      imageHeight: Dimens.view_item_tag_height_small,
      margin: margin,
    );
  }
  
  buildTitleIcon(bool show, String imageName){
    return Offstage(
      offstage: !show,
      child: Image.asset(PdUtil.getImagePath(imageName), width: Dimens.view_item_tag_height_smaller, fit: BoxFit.fitWidth,),
    );
  }
  
  buildDescription(String msg){
    return Padding(
        padding: EdgeInsets.symmetric(vertical: Dimens.gap_view_small),
      child: Text(msg, style: MyTextStyle.LIST_BODY,),
    );
  }

  buildBottomItem(String imageName, String text){
    return Row(
      mainAxisAlignment: MainAxisAlignment.end,
      children: <Widget>[
        Image.asset(PdUtil.getImagePath(imageName), width: Dimens.view_item_icon_height_smallest, fit: BoxFit.fitWidth,),
        Text(" $text", style: MyTextStyle.LIST_BOTTOM,)
      ],
    );
  }


  buildText(String data, Color color, double fontSize) {
    return SmallWidgets.buildText(data, color, fontSize);
  }

  refresh() async{
    pageToken = null;
    list?.clear();
    await loadMore();
  }


  loadMore() async{
    isLoadedData = true;
    List<OscEventListEntity> tempList;
    await httpRepository.getEventList(pageToken: pageToken, userId: authorId).then((resp){
      if(resp != null && resp.success){
        OscBaseListResult<OscEventListEntity> result = resp.result;
        if(result != null){
          tempList = result.items;
          if(pageToken == null){
            list = tempList;
          } else {
            list.addAll(tempList);
          }
          pageToken = result.nextPageToken;
          if(result.requestCount > result.responseCount){
            controller.loadNoData();
          } else {
            controller.loadComplete();
          }
        }
      }
    });

    size = list?.length??0;
    if(mounted) {
      setState(() {
        controller.refreshCompleted();
      });
    }
  }

  jump2PageForResult(Widget page, {bool checkLogin = false}) {
    if(checkLogin){
      if(OscUserManager.getInstance().isLogin()){
        jumpToPageForResult(page);
      } else {
        jumpToPageForResult(LoginPage());
        showTips(StringIds.userNoLogin);
      }
    } else {
      jumpToPageForResult(page);
    }
  }
  jumpToPageForResult(Widget page) {
    NavigatorUtil.pushPageForResult<PopResult>(context, page).then((result) {
      if (result != null) {
        switch (result.id) {
          case PopResult.ID_LOGIN:
            break;
        }
      }
    });
  }

  showTips(String msg){
    PdUtil.showToast(msg: msg);
  }
}
